#from functools import wraps
import subprocess

# 参考：https://www.cnblogs.com/guangdelw/p/17058784.html

# 执行 kubectl get pod mybusybox-csv
POD_STATUS_BY_NAME = f"kubectl get pod %s"  # 状态大概有：ContainerCreating | Running | Completed
POD_DELETE_BY_NAME = f"kubectl delete pod %s"
POD_APPLY_BY_YAML_PATH = f"kubectl apply -f %s"


def log_response(func):
    def wrapper(*args, **kwargs):
        response = func(*args, **kwargs)
        print(f"CLI list:", repr(response))
        return response
    return wrapper


@log_response
def to_cli_list(cli: str) -> list:
    return cli.split(" ")


def subprocess_run(cli: str) -> subprocess.CompletedProcess:
    return subprocess.run(
            args=to_cli_list(cli=cli),
            stdout=subprocess.PIPE,     # 表示重定向shell命令的输出，可以为后面程序所调用
            text=True,                  # 表示将shell命令执行的stdout和stderr当成字符串（python3.8以后默认为bytes类型）
            check=True                  # 表示开启shell命令的执行校验，当shell出任何问题时，都会抛出一个异常
            )    


def get_pod_status_by_name(pod_name: str) -> dict:
    try:
        return_code = subprocess_run(POD_STATUS_BY_NAME % pod_name)
    except Exception as e:
        # 但服务不存在时，报错为: Error from server (NotFound): pods "mybusybox-csv" not found
        print(f"subprocess.run error: %s" % repr(e))
        return None

    #print(type(return_code))
    print("return code:", return_code)
    if return_code.returncode != 0:
        print(f"returncode=%s err" % return_code.returncode)
        return None
    
    data = []
    for line in return_code.stdout.split("\n"):
        if line == '':
            continue
        data.append(line.split())
    # change into dict, like: {'name': 'mybusybox-csv', 'ready': '0/1', 'status': 'completed', 'restarts': '0', 'age': '13d'}
    return {key.lower(): value.lower() for key, value in zip(data[0], data[1])} 



def delete_pod_by_name(pod_name: str): 
    try:
        return_code = subprocess_run(POD_DELETE_BY_NAME % pod_name)
    except Exception as e:
        print(f"subprocess.run error: %s" % repr(e))

    #print(type(return_code))
    print("return code:", return_code)
    #print("\n")
    # return_code: CompletedProcess(args=['kubectl', 'delete', 'pod', 'mybusybox-csv'], returncode=0, stdout='pod "mybusybox-csv" deleted\n')
    if return_code.returncode != 0:
        print(f"returncode=%s err" % return_code.returncode)
        return -1
    
    result = return_code.stdout.split("\n")[0]
    if "deleted" not in result:
        print(f"there is something wrong in pod response: %s" % return_code.stdout)
        return -1
    print(f"pod_name=%s has been deleted success!! " % pod_name)
    return 0



def apply_pod_by_yaml(pod_yaml: str) -> int:
    try:
        return_code = subprocess_run(POD_APPLY_BY_YAML_PATH % pod_yaml)
    except Exception as e:
        print(f"subprocess.run error: %s" % repr(e))
        return -1

    #print(type(return_code))
    print("return code:", return_code)
    #print("\n")
    # return_code: CompletedProcess(args=['kubectl', 'apply', '-f', '/host/template/gwas.yaml'], returncode=0, stdout='pod/mybusybox-csv created\n')
    if return_code.returncode != 0:
        print(f"returncode=%s err" % return_code.returncode)
        return -1
    
    create_result = return_code.stdout.split("\n")[0]
    if "created" not in create_result:
        print(f"there is something wrong in pod response: %s" % return_code.stdout)
        return -1
    print(f"pod_yaml=%s apply success!! please wait a while" % pod_yaml)
    return 0
        


def main():
    pod_name = "mybusybox-csv"
    pod_yaml = "/host/template/gwas.yaml"
    pod_status = get_pod_status_by_name(pod_name=pod_name)

    if pod_status is None:
        '''直接执行启动pod服务'''
        apply_pod_by_yaml(pod_yaml=pod_yaml)
    else:
        '''先删除，再启动'''
        delete_pod_by_name(pod_name=pod_name)
        apply_pod_by_yaml(pod_yaml=pod_yaml)


if __name__ == "__main__":
    main()